package org.example.myleet.rosalind.trie;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class Solution {
    public static void main(String[] args) throws IOException {
        Solution solution = new Solution();
        TrieTree trieTree = new TrieTree();
        String path = solution.getClass().getResource("").getPath() + "example.txt";
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
        String line;
        while (null != (line = br.readLine())) {
            if (line.length() < 1) {
                break;
            }
            trieTree.add(line.trim());
        }
        trieTree.printAdjacentList(null);
    }

    private static final Map<String, Integer> LABEL_MAP_INDEX;

    static {
        LABEL_MAP_INDEX = new HashMap<>(4);
        LABEL_MAP_INDEX.put("A", 0);
        LABEL_MAP_INDEX.put("C", 1);
        LABEL_MAP_INDEX.put("G", 2);
        LABEL_MAP_INDEX.put("T", 3);
    }

    static class TrieTree {
        TrieNode root;
        private int id;

        public TrieTree() {
            id = 1;
            root = new TrieNode(id, "Root");
        }

        private int getNextId() {
            ++id;
            return id;
        }

        public void add(String seq) {
            TrieNode cur = root;
            for (int i = 0; i < seq.length(); ++i) {
                String label = seq.substring(i, i + 1);
                int idx = LABEL_MAP_INDEX.get(label);
                if (null == cur.children[idx]) {
                    cur.children[idx] = new TrieNode(getNextId(), label);
                }
                cur = cur.children[idx];
            }
        }

        //先序遍历
        public void printAdjacentList(TrieNode node) {
            TrieNode cur;
            if (null == node) {
                cur = root;
            } else {
                cur = node;
            }
            for (int i = 0; i < 4; ++i) {
                if (null != cur.children[i]) {
                    System.out.println(cur.id + " " + cur.children[i].id + " " + cur.children[i].label);
                    printAdjacentList(cur.children[i]);
                }
            }
        }
    }

    static class TrieNode {
        int id;
        String label;
        TrieNode[] children;

        public TrieNode(int id, String label) {
            this.id = id;
            this.label = label;
            this.children = new TrieNode[4];
        }
    }
}
